const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const cors = require('cors');  // 引入 cors 模块

const app = express();

// 配置 CORS，允许来自前端端口 8080 的请求
app.use(cors({
  origin: 'http://localhost:8080',  // 前端地址
  methods: ['GET'],
  allowedHeaders: ['Content-Type'],
}));

// 提供静态资源 /faces 路径访问 public/faces 文件夹
app.use('/faces', express.static(path.join(__dirname, 'public/faces')));

// 添加处理 application/json
app.use(express.json());
// 添加处理 application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

// 配置 multer 存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const dir = path.join(__dirname, 'public/faces');
    // 确保目录存在
    if (!fs.existsSync(dir)){
      fs.mkdirSync(dir, { recursive: true });
    }
    cb(null, dir);
  },
  filename: function (req, file, cb) {
    // 打印请求信息，用于调试
    console.log('Request body:', req.body);
    console.log('File:', file);
    
    // 确保用户名存在
    const username = req.body.username || 'unknown';
    cb(null, `${username}.jpg`);
  }
});

const upload = multer({ storage: storage });

// 处理照片上传
app.post('/api/save-photo', upload.single('photo'), (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: '没有收到文件' });
    }
    console.log('File saved:', req.file);
    console.log('Username:', req.body.username);
    res.json({ success: true, message: '照片保存成功' });
  } catch (error) {
    console.error('保存照片时出错:', error);
    res.status(500).json({ error: '保存照片失败' });
  }
});


const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
});